package com.test.dao;

import com.test.entity.User;
import com.test.mapper.UserMapper;
import com.test.util.MyBatisUtil;
import com.util.DatabaseUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;

public class UserDaoTest {

    @Before
    public void initTable() {
        DatabaseUtil.createTestTable();

        DatabaseUtil.truncateTestTable();
    }

    @Test
    public void testCRUD() {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

            // 使用时间戳确保用户名唯一
            String uniqueName = "测试用户_" + System.currentTimeMillis();

            // 1. 插入用户
            User newUser = new User(uniqueName, 22, "test@example.com");
            int insertRows = userMapper.insertUser(newUser);
            System.out.println("插入行数：" + insertRows);
            System.out.println("插入用户ID（自增）：" + newUser.getId());

            // 2. 查询用户
            User queryUser = userMapper.getUserById(newUser.getId());
            System.out.println("查询到的用户：" + queryUser);

            // 3. 更新用户
            userMapper.updateUserAge(uniqueName, 23, "updated@example.com");
            System.out.println("更新完成");

            // 4. 删除用户
            userMapper.deleteUserById(newUser.getId());
            System.out.println("删除完成");

            sqlSession.commit();
        }
    }
}